package b;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import d.ConnectionManager;
import d.QueryCallback;


public class User extends Entity {
	private String name;

	protected User(int id,String name) {
		this.setId(id);
		this.name = name;
	}

	public String getName() { return name; }

	public static User authorizate(String username,String passwd) {
		/*
		StringBuffer passwdMD5 = new StringBuffer();
		try {
			MessageDigest md = java.security.MessageDigest.getInstance("MD5");
			byte[] bytes = md.digest(passwd.getBytes());
			String hexByte;
		    for (byte b : bytes) {
		    	hexByte = Integer.toHexString(0xFF & b);
		    	if(hexByte.length()==1) {
		    		passwdMD5.append('0');
		    	}
		    	passwdMD5.append(hexByte);
		    }
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		*/
		return ConnectionManager.executeQuery("SELECT id,name FROM User WHERE name=? AND passwd=password(?)",new QueryCallback<User>(){
			@Override
			public User processResultset(ResultSet rs) throws SQLException {
				if(rs.next()) {
					return new User(rs.getInt("id"),rs.getString("name"));
				}
				return null;
			}
		},username,passwd);
	}

	public static Entity retrieve(int uniqueId) {
		return ConnectionManager.executeQuery("SELECT id,name FROM User WHERE id=?",new QueryCallback<User>(){
			@Override
			public User processResultset(ResultSet rs) throws SQLException {
				if(rs.next()) {
					return new User(rs.getInt("id"),rs.getString("name"));
				}
				return null;
			}
		},uniqueId);
	}

	@Override
	public boolean save() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void update(Map<String, String> params) {
		// TODO Auto-generated method stub
		
	}
}
